package com.smartum.mpr.business;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smartum.mpr.dao.JobDao;
import com.smartum.mpr.dao.ItemPurchaseDao;
import com.smartum.mpr.dao.JobPurchaseDao;
import com.smartum.mpr.exception.AuthorizationException;
import com.smartum.mpr.exception.DatabaseIntegrityException;
import com.smartum.mpr.exception.NotCorrectPermission;
import com.smartum.mpr.exception.NotExistsTokenException;
import com.smartum.mpr.model.Item;
import com.smartum.mpr.model.Job;
import com.smartum.mpr.model.ItemPurchase;
import com.smartum.mpr.model.JobPurchase;

@Service
public class JobBusiness extends BaseBusiness {

	@Autowired
	private JobDao jobDao;
	@Autowired
	private JobPurchaseDao purchaseDao;

	public void saveJob(Job job) {
		jobDao.save(job);
	}

	public void updateJob(Job job) {
		jobDao.update(job);
	}

	public List<Job> getPublicJobs(Long timestamp, int amount) {
		return jobDao.getPublicJobs(timestamp, amount);
	}

	public List<Job> getUserJobs(Long timestamp, int amount, Long userId) {
		return jobDao.getUserJobs(timestamp, amount, userId);
	}

	public void checkPostPermission(Long userId, Long categoryId) throws DatabaseIntegrityException,
	        AuthorizationException, NotExistsTokenException, NotCorrectPermission {
		JobPurchase purchase = purchaseDao.getJobPurchase(categoryId, userId);
		if (purchase == null) {
			throw new NotCorrectPermission("no_permission_to_post_item");
		}
	}

	public void removePostPermission(Long userId, Long categoryId) throws DatabaseIntegrityException,
	        AuthorizationException, NotExistsTokenException, NotCorrectPermission {
		JobPurchase purchase = purchaseDao.getJobPurchase(categoryId, userId);
		if (purchase == null) {
			throw new NotCorrectPermission("no_permission_to_post_item");
		} else {
			purchaseDao.deletePurchase(purchase);
		}
	}

	public Job getJobById(Long id) {
		return jobDao.get(id);
	}

	public List<Job> searchJobs(Long categoryId, Long subCategoryId, Boolean getHeighest, Long timestamp, int amount,
	        Long countyId) {
		List<Job> jobs = jobDao.getJobsBySearchQuery(categoryId, subCategoryId, getHeighest, timestamp, amount,
		        countyId);

		return jobs;
	}

	public void deleteJob(Long id) {
		jobDao.delete(id);
	}

}
